<?php
/**
 * Hellos Model for Hello World Component
 * 
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_4
 * @license		GNU/GPL
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

/**
 * Hello Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class ChartsModelCharts extends JModel
{
	/**
	 * Charts data array
	 *
	 * @var array
	 */
	var $_data;


	/**
	 * Returns the query
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function _buildQuery()
	{
		$query = ' SELECT * '
			. ' FROM #__menu_indicadores ORDER BY ordering'
		;

		return $query;
	}

	/**
	 * Retrieves the chart data
	 * @return array Array of objects containing the data from the database
	 */
	function getData()
	{
		
		$db =& JFactory::getDBO();

        $query = $this->_buildQuery();

		
		// Lets load the data if it doesn't already exist
		if (empty( $this->_data ))
		{
	        $db->setQuery( $query );
	        $this->_data = $db->loadAssocList();
			$tree=$this->build_tree($this->_data,0,0);
		}
		
		return $tree;
	}
	
	function build_tree(&$unsorted, $start_node, $level)
	 {
	 	//echo $start_node;
	     $out=array();
	     	          
	     foreach($unsorted as $key=>$node) {
	        if ($node['id_padre']==$start_node) {
	        	$node['nivel']=$level;
	        	$out[]=$node;
	        	$out=array_merge($out,$this->build_tree($unsorted, $node['id'],($level+1)));
	        }
	     }
	     return $out;
	 } 

	function getPagination()
	{
	  if (empty($this->_pagination))
	  {
	    // Import the pagination library
	    jimport('joomla.html.pagination');
	    // Prepare the pagination values
	    $total = $this->getTotal();
	    $limitstart = $this->getState('limitstart');
	    $limit = $this->getState('limit');
	    // Create the pagination object
	    $this->_pagination = new JPagination($total,
	    $limitstart,
	    $limit);
	  }
	  return $this->_pagination;
	}
	
	/**
	 * Get number of items
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
	  if (empty($this->_total))
	  {
	    $query = $this->_buildQuery();
	    $this->_total = $this->_getListCount($query);
	  }
	  return $this->_total;
	}

	function move($id,$delta)
	{
	    $db =& JFactory::getDBO();
		global $option;
		// Initialize variables
		$db	=& JFactory::getDBO();
		$row =& $this->getTable('menu_indicadores');
		$row->load($id);
		$row->move($delta,'id_padre ='.$row->id_padre);
	}		

}